package com.iyao_app.mvp.login;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.iyao_app.R;
import com.iyao_app.base.BaseActivity;
import com.iyao_app.entry.DataBean;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.User;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.http.RequestUrl;
import com.iyao_app.im.activity.GuideH5UsActivity;
import com.iyao_app.mvp.completeinfo.CompleteInfoActivity;
import com.iyao_app.mvp.home.MainActivity;
import com.iyao_app.mvp.password.ForgetActivity;
import com.iyao_app.mvp.register.RegisterActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.DbUtil;
import com.iyao_app.view.LetterSpacingTextView;
import com.iyaowoqu.base_library.util.KeyboardUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.RegexUtils;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * 作者 : 胡家兵
 * 时间 : 2017/11/9.
 */

public class LoginActivity extends BaseActivity implements LoginContract.View {

    @BindView(R.id.tv_login_account)
    EditText mTvLoginAccount;
    @BindView(R.id.tv_login_password)
    EditText mTvLoginPassword;
    @BindView(R.id.tv_login)
    LetterSpacingTextView mTvLogin;
    @BindView(R.id.rl_root)
    RelativeLayout mRlRoot;
    @BindView(R.id.tv_fail)
    TextView mTvFail;
    private Bitmap bm;
    private LoginContract.Presenter mPresenter;
    private final int REQUEST_CODE_STORAGE = 100;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //全屏
        setContentView(R.layout.activity_login);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        ButterKnife.bind(this);
        bm = BitmapFactory.decodeResource(this.getResources(), R.mipmap.bg_ditu_denglu);
        BitmapDrawable bd = new BitmapDrawable(this.getResources(), bm);
        mRlRoot.setBackgroundDrawable(bd);
        new LoginPresenter(this);
        // Activity:
        AndPermission.with(this)
                .requestCode(REQUEST_CODE_STORAGE)
                .permission(Permission.STORAGE)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(LoginActivity.this, rationale).show();
                    }
                })
                .callback(this)
                .start();
        initData();

    }

    private void initData() {
        mTvLoginAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mTvFail.getVisibility() == View.VISIBLE) {
                    mTvFail.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mTvLoginPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mTvFail.getVisibility() == View.VISIBLE) {
                    mTvFail.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mTvLoginPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    LogUtil.e("=================");
                    KeyboardUtils.hideSoftInput(LoginActivity.this);
                }

                return false;
            }
        });
    }

    @PermissionYes(REQUEST_CODE_STORAGE)
    private void getMultiYes(@NonNull List<String> grantedPermissions) {
        LogUtil.e("成功");
    }

    @PermissionNo(REQUEST_CODE_STORAGE)
    private void getMultiNo(@NonNull List<String> deniedPermissions) {
        LogUtil.e("failure");
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            AndPermission.defaultSettingDialog(this, 100)
                    .setTitle("权限申请失败")
                    .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
                    .setPositiveButton("好，去设置")
                    .setNegativeButton("拒绝", null)
                    .show();

        }
    }

    @Override
    public void setPresenter(LoginContract.Presenter presenter) {
        mPresenter = presenter;
        mPresenter.start();
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hidProgress() {

    }

    @OnClick({R.id.tv_register, R.id.tv_forget, R.id.tv_login, R.id.tv_agree, R.id.tv_fuwu, R.id.tv_xieyi, R.id.tv_yinsi, R.id.tv_gongyue, R.id.rl_root})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tv_register:
                intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_forget:
                intent = new Intent(this, ForgetActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.noanim, R.anim.exit_leftttoight);
                break;
            case R.id.tv_login:
                login();
                break;
            case R.id.tv_agree:

                break;
            case R.id.tv_fuwu:
                intent = new Intent(this, GuideH5UsActivity.class);
                intent.putExtra(Contants.OTHER_FIELD, "服务条款");
                intent.putExtra(Contants.TYPE, RequestUrl.SERVICE);
                startActivity(intent);
                break;
            case R.id.tv_xieyi:
                intent = new Intent(this, GuideH5UsActivity.class);
                intent.putExtra(Contants.OTHER_FIELD, "用户协议");
                intent.putExtra(Contants.TYPE, RequestUrl.USER_AGREEMENT);
                startActivity(intent);
                break;
            case R.id.tv_yinsi:
                intent = new Intent(this, GuideH5UsActivity.class);
                intent.putExtra(Contants.OTHER_FIELD, "隐私政策");
                intent.putExtra(Contants.TYPE, RequestUrl.PRIVACY_POLICY);
                startActivity(intent);
                break;
            case R.id.tv_gongyue:
                intent = new Intent(this, GuideH5UsActivity.class);
                intent.putExtra(Contants.OTHER_FIELD, "社会公约");
                intent.putExtra(Contants.TYPE, RequestUrl.COMMUNITY_CONVENTION);
                startActivity(intent);
                break;
            case R.id.rl_root:
                mRlRoot.setFocusable(true);
                KeyboardUtils.hideSoftInput(this);

                break;
        }
    }

    private void login() {

        if (TextUtils.isEmpty(mTvLoginAccount.getText().toString().trim()) || TextUtils.isEmpty(mTvLoginPassword.getText().toString().trim()) || !RegexUtils.isMobileExact(mTvLoginAccount.getText().toString().trim())) {
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            mTvFail.setVisibility(View.VISIBLE);
            mTvFail.startAnimation(shake);
            return;
        }
        showDialog();
        NetUtils.getInstance().login(mTvLoginAccount.getText().toString().trim(), mTvLoginPassword.getText().toString().trim(), new NetCallBack() {
            @Override
            public void onSuccess(String message, final int status, final String response, final ResultModel model) {
                LogUtil.e("=mTvLoginAccount===" + response);
                Observable.
                        timer(1, TimeUnit.SECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Long>() {

                            @Override
                            public void accept(Long aLong) throws Exception {
                                closeDialog();

                                if (status == Contants.SUCCESS_CODE) {
                                    DataBean dataBean = JSON.parseObject(response, DataBean.class);
//                                    Gson gson = new Gson();
//                                    DataBean dataBean = gson.fromJson(response, DataBean.class);
                                    if (dataBean.data.userDetail == null) {//完善资料
                                        Intent intent = new Intent(LoginActivity.this, CompleteInfoActivity.class);
                                        intent.putExtra(Contants.TYPE, 0);
                                        intent.putExtra(Contants.OTHER_FIELD, dataBean.data.user);
                                        startActivity(intent);
                                        finish();
                                    } else {
                                        User user = new User();
                                        user.id = dataBean.data.user.id;
                                        user.token = dataBean.data.user.token;
                                        user.nickname = dataBean.data.user.nickname;
                                        user.phone = dataBean.data.user.phone;
                                        user.realname = dataBean.data.user.realname;
                                        user.sex = dataBean.data.user.sex;
                                        user.password = dataBean.data.user.password;
                                        user.avatarUrl = dataBean.data.user.avatarUrl;
                                        user.status = dataBean.data.user.status;

                                        user.openid = dataBean.data.user.openid;
                                        user.invitationCode = dataBean.data.user.invitationCode;
                                        user.source = dataBean.data.user.source;
                                        user.userId = dataBean.data.user.userId != null ? dataBean.data.user.userId : dataBean.data.user.id;
                                        user.birthday = dataBean.data.userDetail.birthday;

                                        user.city = dataBean.data.userDetail.city;
                                        user.descSign = dataBean.data.userDetail.descSign;
                                        user.tags = dataBean.data.userDetail.tags;
                                        user.vioceSignUrl = dataBean.data.userDetail.vioceSignUrl;
                                        user.province = dataBean.data.userDetail.province;
                                        user.district = dataBean.data.userDetail.district;
                                        user.country = dataBean.data.userDetail.country;

                                        DbUtil.updateUserInfo(user);
                                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                        startActivity(intent);
                                        finish();
                                        overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);
                                        loginYun();
                                    }
                                } else {
                                    Animation shake = AnimationUtils.loadAnimation(LoginActivity.this, R.anim.shake);
                                    mTvFail.setVisibility(View.VISIBLE);
                                    mTvFail.startAnimation(shake);
                                }
                            }
                        });

            }

            @Override
            public void onFail(String message, int status) {
                LogUtil.e("网络不好");
                closeDialog();
            }
        }, null);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BitmapDrawable bd = (BitmapDrawable) mRlRoot.getBackground();
        bm = null;
        mRlRoot.setBackgroundDrawable(null);
        bd.setCallback(null);
        bd.getBitmap().recycle();
    }


    /**
     * 云信的登录
     */
    public void loginYun() {
        NIMClient.getService(AuthService.class).login(loginInfo())
                .setCallback(new RequestCallback() {
                    @Override
                    public void onSuccess(Object o) {
                        LogUtil.e("云信登录成功" + o);
                    }

                    @Override
                    public void onFailed(int i) {
                        LogUtil.e("云信登录失败：" + i);
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        LogUtil.e("云信登录异常" + throwable);
                    }
                });
    }

    private LoginInfo loginInfo() {

        User user = DbUtil.getUser();
        if (user == null) return null;
        return new LoginInfo(DbUtil.getUser().id, DbUtil.getUser().token);
    }

}
